<script setup lang="ts">
import { ref, onMounted, computed, onBeforeUnmount } from "vue"
import { storeToRefs } from "pinia"
import { getUUID, getLoginStatus } from "@/api/qyyjt/index"
import { updateBindStatus } from "@/api/login/index"
import { useQyyjtStore } from "@/store/modules/qyyjt"
import { useUserStore } from "@/store/modules/user"
import VueQrcode from "vue-qrcode"

defineOptions({
  name: "QYYJT"
})
// const props = defineProps(["isBinded"])

const QyyjtStore = useQyyjtStore()
const userStore = useUserStore()
const { userDetail } = storeToRefs(userStore)
const { quser } = storeToRefs(QyyjtStore)
const qrcode_uuid = ref("")
/** 绑定企业预警通账号 */
const showQRCode = async () => {
  let resp = await getUUID()
  qrcode_uuid.value = resp.data.data
  loginStatus()
}
/**企业预警通二维码 */
const qrcode_value = computed(() => {
  return "https://cdn.finchina.com/app/h5/app_scan_no_installs/install.html?uuid=" + qrcode_uuid.value
})
/**扫码状态轮询 */
let isScanned = ref("请用企业预警通app扫码登录")
let timer: any = null

/**轮询定时器 */
const loginStatus = async () => {
  // 点击开启轮询
  timer = setInterval(async () => {
    let resp = await QyyjtStore.loginStatus({ uuid: qrcode_uuid.value })
    console.log("xxx", resp)
    if (resp.status === 113) {
      isScanned.value = "已成功登录"
      // 登录成功以后清除掉timer
      clearInterval(timer)
      // 修改变量状态，显示页面变换
      userDetail.value.hasQUser = true
      // 修改user数据库，改为已绑定
      await updateBindStatus(true)
      QyyjtStore.bindQuser({ ...resp })
    } else if (resp.status === 112) {
      isScanned.value = "扫码成功，请在手机端确认登录"
    } else {
      isScanned.value = "请用企业预警通app扫码登录"
    }
  }, 2000)
}
/**销毁清除定时器 */
onBeforeUnmount(() => {
  clearInterval(timer)
  // timer = null
})
onMounted(() => {
  QyyjtStore.getQuser()
})
</script>

<template>
  <!-- <template v-if="userDetail.hasQuser"> -->
  <template v-if="userDetail.hasQUser">
    <el-form :model="quser.basic_info" class="qinfo" label-width="auto">
      <el-form-item label="账户昵称">
        <el-input disabled v-model="quser.basic_info.nickname"></el-input>
      </el-form-item>
      <el-form-item label="账户手机号">
        <el-input disabled v-model="quser.basic_info.phone"></el-input>
      </el-form-item>
      <el-form-item label="账户注册邮箱">
        <el-input disabled v-model="quser.basic_info.email"></el-input>
      </el-form-item>
    </el-form>
  </template>
  <template v-else>
    <div class="qrcode" v-if="qrcode_uuid">
      <VueQrcode :value="qrcode_value" type="image/webp" :color="{ dark: '#000000ff', light: '#ffffffff' }"></VueQrcode>
      {{ isScanned }}
    </div>
    <div class="qrcode" v-else>
      <el-button type="primary" @click="showQRCode">绑定企业预警通账号</el-button>
    </div>
  </template>
</template>

<style lang="scss" scoped>
.qinfo {
  margin: 0 auto;
  max-width: 600px;
}

.qrcode {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}
</style>
